package qf.sail.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import qf.sail.dao.GoodDao;
import qf.sail.entity.Account;
import qf.sail.entity.Good;
import qf.sail.util.DBUtil;

import java.sql.SQLException;
import java.util.List;

public class GoodDaoImpl implements GoodDao {

    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    /**
     * 获取指定数量的热销商品
     * @param count 指定数量
     * @return
     */
    public List<Good> getMaxSalesGood(int count){
        String sql = "select * from good order by sales_volume desc limit ?";
        Object[] params = {count};
        List<Good> goods = null;
        try {
            goods = queryRunner.query(sql, DBUtil.getBeanListHandler(Good.class),params);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return goods;
    }

    /**
     * 获取指定数量,指定性别的热销商品
     * @param count
     * @param sexType
     * @return
     */
    @Override
    public List<Good> getMaxSalesGood(int count, int sexType) {
        String sql = "select * from good where sex_type = ? order by sales_volume desc limit ?";
        Object[] params = {sexType,count};
        List<Good> goods = null;
        try {
            goods = queryRunner.query(sql, DBUtil.getBeanListHandler(Good.class),params);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return goods;
    }

    @Override
    public Good getGoodById(Long id) {
        String sql = "select * from good where id = ? ";
        Object[] params = {id};
        Good good = null;
        try {
            good = queryRunner.query(sql, DBUtil.getBeanHandler(Good.class),params);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return good;
    }

    /**
     * 更新商品存货跟销量
     * @param inventory
     * @param salesVolume
     * @param id
     * @return
     */
    @Override
    public int updateGood(int inventory, int salesVolume, long id) {
        String sql = "update good set inventory = ?,sales_volume = ? where id = ?";
        Object[] params = {inventory,salesVolume,id};
        try {
            int update = queryRunner.update(sql,params);
            return update;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 0;
        }
    }
}
